/**
 * 
 */
package org.adorsys.aderp.cash.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.adorsys.aderp.cash.domain.CashReceipt;
import org.adorsys.aderp.cash.domain.CashRegItem;
import org.adorsys.aderp.cash.domain.CashRegister;
import org.adorsys.aderp.cash.domain.PaymentType;
import org.adorsys.aderp.cash.service.CashReceiptService;
import org.adorsys.aderp.cash.service.CashRegItemService;
import org.adorsys.aderp.cash.service.CashRegisterService;
import org.adorsys.aderp.cash.service.PaymentTypeService;
import org.adorsys.aderp.cash.work.cashstate.BasicCashRegStateMaintainerUtil;
import org.adorsys.aderp.cash.work.cashstate.CashRegStateMaintainer;
import org.adorsys.aderp.cash.work.encashment.BasicEncashment;
import org.adorsys.aderp.cash.work.encashment.EncashmentSession;
import org.adorsys.aderp.jpa.security.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

/**
 * @author Boris Waguia
 *
 */
privileged aspect CollectController_Roo_Controller {
	@Autowired
	private CashRegItemService CollectController.cashRegItemService;
	@Autowired
    CashReceiptService CollectController.cashReceiptService;
	@Autowired
    CashRegisterService CollectController.cashRegisterService;
    
    @Autowired
    PaymentTypeService CollectController.paymentTypeService;
	
    @Resource
	private volatile CashRegStateMaintainer CollectController.cashRegStateMaintainer;
    
	@RequestMapping(method = RequestMethod.POST,value="/cashregitems")
    public java.lang.String CollectController.createCashRegItem(@Valid CashRegItem cashRegItem, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("cashRegItem", cashRegItem);
            return "collects/cashregitems/create";
        }
        uiModel.asMap().clear();
        cashRegItemService.saveCashRegItem(cashRegItem);
        //add the cash register item to the session manager
        BasicEncashment.getActiveEncashmentSession().addCashRegItem(cashRegItem);
        System.out.println(new BasicEncashment().toString());
        return "redirect:/collects/cashregitems/" + encodeUrlPathSegment(cashRegItem.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(params = "form",value="/cashregitems", method = RequestMethod.GET)
    public java.lang.String CollectController.createCashRegItemForm(Model uiModel) {
        uiModel.addAttribute("cashRegItem", new CashRegItem());
        return "collects/cashregitems/create";
    }
    
    @RequestMapping(value = "/cashregitems/{id}", method = RequestMethod.GET)
    public java.lang.String CollectController.showCashRegItem(@PathVariable("id") java.lang.Long id, Model uiModel) {
        uiModel.addAttribute("cashregitem", cashRegItemService.findCashRegItem(id));
        uiModel.addAttribute("itemId", id);
        return "collects/cashregitems/show";
    }
    
    @RequestMapping(value="/cashregitems",method = RequestMethod.GET)
    public java.lang.String CollectController.listCashRegItem(@RequestParam(value = "page", required = false) java.lang.Integer page, @RequestParam(value = "size", required = false) java.lang.Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("cashregitems", cashRegItemService.findCashRegItemEntries(firstResult, sizeNo));
            float nrOfPages = (float) cashRegItemService.countAllCashRegItems() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("cashregitems", cashRegItemService.findAllCashRegItems());
        }
        return "collects/cashregitems/list";
    }
    
    @RequestMapping(value = "/cashregitems",method = RequestMethod.PUT)
    public java.lang.String CollectController.updateCashRegItem(@Valid CashRegItem cashRegItem, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("cashRegItem", cashRegItem);
            return "collects/cashregitems/update";
        }
        uiModel.asMap().clear();
        cashRegItemService.updateCashRegItem(cashRegItem);
        return "redirect:/collects/cashregitems/" + encodeUrlPathSegment(cashRegItem.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(value = "/cashregitems/{id}", params = "form", method = RequestMethod.GET)
    public java.lang.String CollectController.updateFormCashRegItem(@PathVariable("id") java.lang.Long id, Model uiModel) {
        uiModel.addAttribute("cashRegItem", cashRegItemService.findCashRegItem(id));
        return "collects/cashregitems/update";
    }
    
    @RequestMapping(value = "/cashregitems/{id}", method = RequestMethod.DELETE)
    public java.lang.String CollectController.deleteCashRegItem(@PathVariable("id") java.lang.Long id, @RequestParam(value = "page", required = false) java.lang.Integer page, @RequestParam(value = "size", required = false) java.lang.Integer size, Model uiModel) {
        CashRegItem cashRegItem = cashRegItemService.findCashRegItem(id);
        cashRegItemService.deleteCashRegItem(cashRegItem);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/collects/cashregitems";
    }
    
    @ModelAttribute("cashregitems")
    public Collection<CashRegItem> CollectController.populateCashRegItems(HttpServletRequest request) {
//        return cashRegItemService.findAllCashRegItems();
    	EncashmentSession activeEncashmentSession = BasicEncashment.getActiveEncashmentSession();
    	if(activeEncashmentSession == null){
    		activeEncashmentSession = new EncashmentSession(request.getSession(false).getId(),new Date(),SecurityUtils.getUserName());
            BasicEncashment.addEncashmentSession(activeEncashmentSession);
    	}
    	//TODO check whether there are multiples actives encashment sessions, and send all cash register item to the view
    	if(activeEncashmentSession.getCashRegItems() == null) return new ArrayList<CashRegItem>();
    	return activeEncashmentSession.getCashRegItems();
    }

    
    java.lang.String CollectController.encodeUrlPathSegment(java.lang.String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
    /**
     * ============================================
     */
    
    @RequestMapping(method = RequestMethod.POST,value="/cashreceipts")
    public java.lang.String CollectController.createCashReceipt(@Valid CashReceipt cashReceipt, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("cashReceipt", cashReceipt);
            addDateTimeFormatPatterns(uiModel);
            return "collects/cashreceipts/create";
        }
        uiModel.asMap().clear();
        cashReceiptService.saveCashReceipt(cashReceipt);
        return "redirect:/collects/cashreceipts/" + encodeUrlPathSegment(cashReceipt.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(params = "form", method = RequestMethod.GET,value="/cashreceipts")
    public java.lang.String CollectController.createCashReceiptForm(CashReceipt cashReceipt , Model uiModel) {
//        uiModel.addAttribute("cashReceipt", new CashReceipt());
    	uiModel.addAttribute("cashReceipt", cashReceipt);
    	addDateTimeFormatPatterns(uiModel);
        return "collects/cashreceipts/create";
    }
    
    
    @RequestMapping(value="/cashreceipts",method = RequestMethod.PUT)
    public java.lang.String CollectController.updateCashReceipt(@Valid CashReceipt cashReceipt, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("cashReceipt", cashReceipt);
            addDateTimeFormatPatterns(uiModel);
            return "collects/cashreceipts/update";
        }
        uiModel.asMap().clear();
        cashReceiptService.updateCashReceipt(cashReceipt);
        return "redirect:/collects/cashreceipts/" + encodeUrlPathSegment(cashReceipt.getId().toString(), httpServletRequest);
    }
    @RequestMapping(value = "/cashreceipts/{id}", method = RequestMethod.GET)
    public java.lang.String CollectController.showCashReceipt(@PathVariable("id") java.lang.Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("cashreceipt", cashReceiptService.findCashReceipt(id));
        uiModel.addAttribute("itemId", id);
        return "cashreceipts/show";
    }
    public java.lang.String CollectController.updateCashReceiptForm(CashReceipt cashReceipt, Model uiModel) {
        if(cashReceipt == null) cashReceipt = new CashReceipt();
    	uiModel.addAttribute("cashReceipt", cashReceipt);
        addDateTimeFormatPatterns(uiModel);
        return "collects/cashreceipts/update";
    }
    
    void CollectController.addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("cashReceipt_cashdate_date_format", "dd-MM-yyyy HH:mm:ss");
    }
    
    @ModelAttribute("cashregisters")
    public Collection<CashRegister> CollectController.populateCashRegisters() {
//        return cashRegisterService.findAllCashRegisters();
    	return BasicCashRegStateMaintainerUtil.
    			getOpenedCash(cashRegStateMaintainer.getFullDayCashRegisters());
    }
    
    @ModelAttribute("paymenttypes")
    public Collection<PaymentType> CollectController.populatePaymentTypes() {
        return paymentTypeService.findAllPaymentTypes();
    }
}
